package com.ccys.common.third.push.huawei;


import com.alibaba.fastjson.JSONObject;

import com.ccys.common.third.push.huawei.push.android.*;
import com.ccys.common.third.push.huawei.push.exception.HuaweiMesssagingException;
import com.ccys.common.third.push.huawei.push.message.AndroidConfig;
import com.ccys.common.third.push.huawei.push.message.Message;
import com.ccys.common.third.push.huawei.push.message.Notification;
import com.ccys.common.third.push.huawei.push.message.TopicMessage;
import com.ccys.common.third.push.huawei.push.messaging.HuaweiApp;
import com.ccys.common.third.push.huawei.push.messaging.HuaweiMessaging;
import com.ccys.common.third.push.huawei.push.model.Importance;
import com.ccys.common.third.push.huawei.push.model.Urgency;
import com.ccys.common.third.push.huawei.push.model.Visibility;
import com.ccys.common.third.push.huawei.push.reponse.SendResponse;
import com.ccys.common.third.push.huawei.push.util.InitAppUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * Created with IDEA
 * @author:huxi
 * Date:2020/8/1
 * Time:6:50 PM
 */
@Slf4j
public class HuaWeiPush {

    /*public static void main(String[] args) throws HuaweiMesssagingException {
        net.sf.json.JSONObject json = new net.sf.json.JSONObject();
        json.put("key","key");
        json.put("value","value");
//        pushToByToken("测试消息",json.toString(),"0a0000055af3ab30300007623500CN01");
//        pushToByTag("标签测试",json.toString(),"member");
    }*/

    @SuppressWarnings("all")
    public static void pushToByToken(String title,String msg, String hideMsg, List<String> tokenList) throws HuaweiMesssagingException {
        HuaweiApp app = InitAppUtils.initializeApp();
        HuaweiMessaging huaweiMessaging = HuaweiMessaging.getInstance(app);

        //隐藏消息处理
        if(StringUtils.isNotBlank(hideMsg)){
            JSONObject json = JSONObject.parseObject(hideMsg);
            Set<String> keySet = json.keySet();
            StringBuilder sb = new StringBuilder();
            for(String key:keySet){
                sb.append("S.").append(key).append("=").append(json.getString(key)).append(";");
            }
            hideMsg = sb.toString();

        }else{
            hideMsg = "";
        }

        Notification notification = Notification.builder()
            .setTitle("新加坡在线医疗平台")
            .setBody(msg)
            .build();

        JSONObject multiLangKey = new JSONObject();
        JSONObject titleKey = new JSONObject();
        titleKey.put("en","好友请求");
        JSONObject bodyKey = new JSONObject();
        titleKey.put("en","My name is %s, I am from %s.");
        multiLangKey.put("key1", titleKey);
        multiLangKey.put("key2", bodyKey);

        LightSettings lightSettings = LightSettings.builder().setColor(Color.builder().setAlpha(0f).setRed(0f).setBlue(1f).setGreen(1f).build())
                .setLightOnDuration("3.5")
                .setLightOffDuration("5S")
                .build();

        AndroidNotification androidNotification = AndroidNotification.builder().setIcon("/raw/ic_launcher2")
                .setColor("#AACCDD")
                .setSound("/raw/shake")
                .setDefaultSound(true)
                .setTag("tagBoom")
                .setClickAction(ClickAction.builder().setType(1)
                        .build())
                .setBodyLocKey("M.String.body")
                .addBodyLocArgs("boy").addBodyLocArgs("dog")
                .setTitleLocKey("M.String.title")
                .addTitleLocArgs("Girl").addTitleLocArgs("Cat")
                .setChannelId("Your Channel ID")
                .setNotifySummary("some summary")
                .setMultiLangkey(multiLangKey)
                .setStyle(1)
                //app 通知栏实际展示标题
                .setBigTitle(title)
                //app 通知栏实际展示内容
                .setBigBody(msg)
                .setAutoClear(86400000)
                .setNotifyId(486)
                .setGroup("Group1")
                .setImportance(Importance.LOW.getValue())
                .setLightSettings(lightSettings)
                .setBadge(BadgeNotification.builder().setAddNum(1).setBadgeClass("Classic").build())
                .setVisibility(Visibility.PUBLIC.getValue())
                //true  普通展示，false 透传消息
                .setForegroundShow(false)
                .addInboxContent("content1").addInboxContent("content2").addInboxContent("content3").addInboxContent("content4").addInboxContent("content5")
                .addButton(Button.builder().setName("button1").setActionType(0).build())
                .addButton(Button.builder().setName("button2").setActionType(1).setIntentType(0).setIntent("https://com.huawei.hms.hmsdemo/deeplink").build())
                .addButton(Button.builder().setName("button3").setActionType(4).setData("your share link").build())
                .build();

        AndroidConfig androidConfig = AndroidConfig.builder().setCollapseKey(-1)
                .setUrgency(Urgency.HIGH.getValue())
                .setTtl("10000s")
                .setBiTag("the_sample_bi_tag_for_receipt_service")
                .setNotification(androidNotification)
                .build();

        Message message = Message.builder().setNotification(notification)
                //此处设置隐藏消息  测试有效
                .setData(hideMsg)
                .setAndroidConfig(androidConfig)
                .addAllToken(tokenList)
                .build();

        SendResponse response = huaweiMessaging.sendMessage(message);

        log.info("huawei返回结果:{}",response.getCode());
        log.info("huawei返回信息:{}",response.getMsg());

    }

    @SuppressWarnings("all")
    public static void pushToByTag(String msg,String hideMsg,String tag) throws HuaweiMesssagingException {
        HuaweiApp app = InitAppUtils.initializeApp();
        HuaweiMessaging huaweiMessaging = HuaweiMessaging.getInstance(app);

        //隐藏消息处理
        if(StringUtils.isNotBlank(hideMsg)){
            JSONObject json = JSONObject.parseObject(hideMsg);
            Set<String> keySet = json.keySet();
            StringBuilder sb = new StringBuilder();
            for(String key:keySet){
                sb.append("S.").append(key).append("=").append(json.getString(key)).append(";");
            }
            hideMsg = sb.toString();

        }else{
            hideMsg = "";
        }

        Notification notification = Notification.builder().setTitle("新加坡在线医疗平台")
                .setBody(msg)
                .build();

        JSONObject multiLangKey = new JSONObject();
        JSONObject titleKey = new JSONObject();
        titleKey.put("en","好友请求");
        JSONObject bodyKey = new JSONObject();
        titleKey.put("en","My name is %s, I am from %s.");
        multiLangKey.put("key1", titleKey);
        multiLangKey.put("key2", bodyKey);

        LightSettings lightSettings = LightSettings.builder().setColor(Color.builder().setAlpha(0f).setRed(0f).setBlue(1f).setGreen(1f).build())
                .setLightOnDuration("3.5")
                .setLightOffDuration("5S")
                .build();

        AndroidNotification androidNotification = AndroidNotification.builder().setIcon("/raw/ic_launcher2")
                .setColor("#AACCDD")
                .setSound("/raw/shake")
                .setDefaultSound(true)
                .setTag("tagBoom")
                .setClickAction(ClickAction.builder().setType(1)
                        .setIntent("intent://com.ccys.convenience/ccys?#Intent;scheme=pushscheme;action=com.ccys.convenience.LunchActivity;launchFlags=0x4000000;"+hideMsg+"end")
                        .build())
                .setBodyLocKey("M.String.body")
                .addBodyLocArgs("boy").addBodyLocArgs("dog")
                .setTitleLocKey("M.String.title")
                .addTitleLocArgs("Girl").addTitleLocArgs("Cat")
                .setChannelId("Your Channel ID")
                .setNotifySummary("some summary")
                .setMultiLangkey(multiLangKey)
                .setStyle(1)
                .setBigTitle("Big Boom Title")
                .setBigBody("Big Boom Body")
                .setAutoClear(86400000)
                .setNotifyId(486)
                .setGroup("Group1")
                .setImportance(Importance.LOW.getValue())
                .setLightSettings(lightSettings)
                .setBadge(BadgeNotification.builder().setAddNum(1).setBadgeClass("Classic").build())
                .setVisibility(Visibility.PUBLIC.getValue())
                .setForegroundShow(true)
                .addInboxContent("content1").addInboxContent("content2").addInboxContent("content3").addInboxContent("content4").addInboxContent("content5")
                .addButton(Button.builder().setName("button1").setActionType(0).build())
                .addButton(Button.builder().setName("button2").setActionType(1).setIntentType(0).setIntent("https://com.huawei.hms.hmsdemo/deeplink").build())
                .addButton(Button.builder().setName("button3").setActionType(4).setData("your share link").build())
                .build();

        AndroidConfig androidConfig = AndroidConfig.builder().setCollapseKey(-1)
                .setUrgency(Urgency.HIGH.getValue())
                .setTtl("10000s")
                .setBiTag("the_sample_bi_tag_for_receipt_service")
                .setNotification(androidNotification)
                .build();

        Message message = Message.builder().setNotification(notification)
                .setAndroidConfig(androidConfig)
                .setTopic(tag)
                .build();


        SendResponse response = huaweiMessaging.sendMessage(message);

        log.info("huawei返回结果:{}",response.getCode());
        log.info("huawei返回信息:{}",response.getMsg());
    }

    /**
    * 订阅（将用户加入到分组）
    * @author      hx
    * @return
    * @exception
    * @date        2020/8/4 9:21 PM
    */
    public static void subscribeTopic(String token,String tag) throws HuaweiMesssagingException {
        HuaweiApp app = InitAppUtils.initializeApp();
        HuaweiMessaging huaweiMessaging = HuaweiMessaging.getInstance(app);
        TopicMessage topicMessage = TopicMessage.builder().setTopic(tag).addToken(token).build();
        SendResponse sendResponse = huaweiMessaging.subscribeTopic(topicMessage);
        log.info("订阅结果:{}",sendResponse.getCode());
        log.info("订阅返回:{}",sendResponse.getMsg());
    }

       /**
        * @description 发送隐藏消息，透传消息
        * @param body 隐藏消息json格式
        * @param token 接收人token
        * @date     2024/1/17
        * @author   cloud fly
        */
    public static void sendTransparent(String token, String body) throws HuaweiMesssagingException {
        HuaweiApp app = InitAppUtils.initializeApp();
        HuaweiMessaging huaweiMessaging = HuaweiMessaging.getInstance(app);

        AndroidConfig androidConfig = AndroidConfig.builder().setCollapseKey(-1)
            .setUrgency(Urgency.HIGH.getValue())
            .setTtl("10000s")
            .setBiTag("the_sample_bi_tag_for_receipt_service")
            .build();


        Message message = Message.builder()
            .setData(body)
            .setAndroidConfig(androidConfig)
            .addToken(token)
            .build();
        SendResponse response = huaweiMessaging.sendMessage(message);
        log.info("huawei返回结果:{}",response.getCode());
        log.info("huawei返回信息:{}",response.getMsg());
    }

}
